<!--库存盘点-->
<template>
  <div class="inventory-count-container">
    <!-- 筛选区域 -->
    <div class="controls-section">
        <button class="btn-new" @click="onAdd">新建</button>
        <div class="filters">
            <div class="filter-item">
                <label>关键词</label>
                <input type="text" placeholder="请输入盘点编号" v-model="query.checkNo">
            </div>
            <div class="filter-item">
                <label>盘点结果</label>
                <select v-model="query.checkResult">
                    <option value="">全部</option>
                    <option :value="0">盘盈</option>
                    <option :value="1">盘亏</option>
                    <option :value="2">正常</option>
                </select>
            </div>
        </div>
        <div class="actions">
            <button class="btn-primary" @click="onSearch">搜索</button>
            <button class="btn-secondary" @click="onReset">重置</button>
        </div>
    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <table>
        <thead>
          <tr>
            <th><input type="checkbox" v-model="allSelected"></th>
            <th>盘点编号</th>
            <th>盘点时间</th>
            <th>盘点产品数</th>
            <th>库存数量</th>
            <th>盘点总数</th>
            <th>盈亏数量</th>
            <th>盘点结果</th>
            <th>盘点人</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading">
            <td colspan="9" style="text-align: center; padding: 20px;">加载中...</td>
          </tr>
          <tr v-else-if="counts.length === 0">
            <td colspan="9" style="text-align: center; padding: 20px;">暂无数据</td>
          </tr>
          <tr v-for="(item, index) in counts" :key="index" v-else>
            <td><input type="checkbox" v-model="item.selected"></td>
            <td class="link-style" @click="viewDetail(item)">{{ item.checkNo || '-' }}</td>
            <td>{{ getDisplayCheckTime(item) }}</td>
            <td>{{ item.productCount || '-' }}</td>
            <td>{{ item.stockQuantity || '-' }}</td>
            <td>{{ item.checkTotal || '-' }}</td>
            <td :class="getProfitLossClass(item.profitLoss)">{{ formatProfitLoss(item.profitLoss) }}</td>
            <td><span :class="getResultClass(item.checkResult)">{{ getResultText(item.checkResult) }}</span></td>
            <td>{{ item.checker || item.uId || '-' }}</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 底部区域 -->
    <div class="footer-section">
      <div class="footer-left">
        <input type="checkbox" v-model="allSelected">
        <label>全选</label>
        <button class="btn-secondary" @click="onExport">导出</button>
      </div>
      <div class="pagination-info">
        共 {{ total }} 条记录，第 {{ query.current }} / {{ totalPages || 1 }} 页
        <span v-if="total > 0">（显示第 {{ getPageRange().start }}-{{ getPageRange().end }} 条）</span>
      </div>
      <div class="pagination">
        <button @click="onPageChange(query.current - 1)" :disabled="query.current === 1">&lt;</button>
        <button v-for="page in totalPages" :key="page" @click="onPageChange(page)" :class="{ active: query.current === page }">{{ page }}</button>
        <button @click="onPageChange(query.current + 1)" :disabled="query.current === totalPages">&gt;</button>
        <select v-model.number="query.size" @change="onPageSizeChange">
          <option value="5">5条/页</option>
          <option value="10">10条/页</option>
          <option value="20">20条/页</option>
          <option value="50">50条/页</option>
        </select>
      </div>
    </div>

    <!-- 新增弹窗 -->
    <el-dialog v-model="addVisible" title="新建库存盘点" width="600px">
      <div class="form-grid">
        <div class="form-item">
          <div class="label">盘点编号</div>
          <div class="field"><el-input v-model="addForm.checkNo" placeholder="系统自动生成" disabled /></div>
        </div>
        <div class="form-item">
          <div class="label">盘点人</div>
          <div class="field">
            <el-select v-model="addForm.uId" placeholder="请选择" filterable :loading="userLoading">
              <el-option v-for="u in userOptions" :key="u.id" :label="u.realName || u.real_name || u.username || u.name || ('用户' + u.id)" :value="u.id" />
            </el-select>
          </div>
        </div>
        <div class="form-item">
          <div class="label">盘点时间</div>
          <div class="field"><el-date-picker v-model="addForm.checkTime" type="date" placeholder="选择盘点时间" format="YYYY-MM-DD" value-format="YYYY-MM-DD" /></div>
        </div>
        <div class="form-item">
          <div class="label">盘点产品数</div>
          <div class="field"><el-input-number v-model="addForm.productCount" :min="1" /></div>
        </div>
        <div class="form-item">
          <div class="label">库存数量</div>
          <div class="field"><el-input-number v-model="addForm.stockQuantity" :min="0" /></div>
        </div>
        <div class="form-item">
          <div class="label">盘点总数</div>
          <div class="field"><el-input-number v-model="addForm.checkTotal" :min="0" /></div>
        </div>
        <div class="form-item">
          <div class="label">备注</div>
          <div class="field"><el-input v-model="addForm.remark" type="textarea" /></div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitAdd">提 交</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 详情弹窗 -->
    <el-dialog v-model="detailVisible" title="库存盘点详情" width="720px">
      <div class="detail-grid">
        <div class="detail-item">
          <div class="label">盘点编号</div>
          <div class="value">{{ detailData.checkNo || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">盘点时间</div>
          <div class="value">{{ getDisplayCheckTime(detailData) || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">盘点产品数</div>
          <div class="value">{{ detailData.productCount || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">库存数量</div>
          <div class="value">{{ detailData.stockQuantity || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">盘点总数</div>
          <div class="value">{{ detailData.checkTotal || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">盈亏数量</div>
          <div class="value" :class="getProfitLossClass(detailData.profitLoss)">{{ formatProfitLoss(detailData.profitLoss) || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">盘点结果</div>
          <div class="value"><span :class="getResultClass(detailData.checkResult)">{{ getResultText(detailData.checkResult) || '-' }}</span></div>
        </div>
        <div class="detail-item">
          <div class="label">盘点人</div>
          <div class="value">{{ detailData.checker || detailData.uId || '-' }}</div>
        </div>
        <div class="detail-item">
          <div class="label">备注</div>
          <div class="value">{{ detailData.remark || '-' }}</div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailVisible = false">关 闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { pageInventoryCheck, addInventoryCheck, getInventoryCheckDetail, exportInventoryCheck } from '@/api/warehouse/InventoryCheck'
import { ElMessage } from 'element-plus'
import { listUsers } from '@/api/basic'

export default {
  name: 'InventoryCount',
  data() {
    return {
      loading: false,
      // 查询条件
      query: {
        checkNo: '',
        checkResult: '',
        current: 1,
        size: 5, // 默认每页显示5条数据
      },
      // 分页数据
      total: 0,
      counts: [],
      // 新增弹窗
      addVisible: false,
      addForm: {
        checkNo: '',
        uId: '',
        checkTime: '',
        productCount: 1,
        stockQuantity: 0,
        checkTotal: 0,
        remark: ''
      },
      userOptions: [],
      userLoading: false,
      // 详情弹窗
      detailVisible: false,
      detailData: {}
    };
  },
  computed: {
    allSelected: {
      get() {
        return this.counts.length > 0 && this.counts.every(item => item.selected);
      },
      set(value) {
        this.counts.forEach(item => {
          item.selected = value;
        });
      }
    },
    totalPages() {
      return Math.ceil(this.total / this.query.size);
    }
  },
  mounted() {
    this.fetchList()
  },
  methods: {
    async fetchList() {
      try {
        this.loading = true
        const payload = {
          checkNo: this.query.checkNo || undefined,
          checkResult: this.query.checkResult === '' ? undefined : Number(this.query.checkResult),
          current: this.query.current,
          size: this.query.size,
        }
        const res = await pageInventoryCheck(payload)
        console.log('API响应:', res.data)
        
        const data = res.data?.data || {}
        let records = []
        
        // 处理嵌套的数据结构 - 适配后端返回的格式
        if (data.records && Array.isArray(data.records)) {
          if (data.records.length > 0 && data.records[0].records) {
            // 嵌套结构：data.records[0].records
            records = data.records[0].records || []
            this.total = data.records[0].total || 0
          } else {
            // 直接结构：data.records
            records = data.records || []
            this.total = data.total || 0
          }
        } else {
          records = data.list || []
          this.total = data.total || 0
        }
        
        this.counts = records.map(r => ({ ...r, selected: false }))
        console.log('解析后的数据:', this.counts)
        
        // 调试：显示每个记录的盘点时间
        this.counts.forEach((item, index) => {
          console.log(`记录${index + 1}的盘点时间:`, item.checkTime, typeof item.checkTime)
        })
      } catch (error) {
        console.error('获取库存盘点列表失败:', error)
        ElMessage.error('获取库存盘点列表失败')
      } finally {
        this.loading = false
      }
    },

    async fetchUsers() {
      try {
        this.userLoading = true
        const res = await listUsers()
        const list = res.data?.data?.records || res.data?.data || res.data || []
        this.userOptions = Array.isArray(list) ? list : []
        // 若返回为空，走兜底
        if (!this.userOptions.length) {
          try {
            const res2 = await pageInventoryCheck({ current: 1, size: 200 })
            const data = res2.data?.data || {}
            let records = []
            if (data.records && Array.isArray(data.records)) {
              if (data.records.length > 0 && data.records[0].records) {
                records = data.records[0].records || []
              } else {
                records = data.records || []
              }
            } else {
              records = data.list || []
            }
            const map = new Map()
            records.forEach(r => {
              const id = r.uId || r.uid || r.userId
              const name = r.checker || r.username || r.realName || r.real_name
              if (id && !map.has(id)) map.set(id, name || `用户${id}`)
            })
            this.userOptions = Array.from(map, ([id, name]) => ({ id, realName: name }))
          } catch { /* 忽略 */ }
        }
      } catch (e) {
        // 接口失败同样尝试兜底
        try {
          const res2 = await pageInventoryCheck({ current: 1, size: 200 })
          const data = res2.data?.data || {}
          let records = []
          if (data.records && Array.isArray(data.records)) {
            if (data.records.length > 0 && data.records[0].records) {
              records = data.records[0].records || []
            } else {
              records = data.records || []
            }
          } else {
            records = data.list || []
          }
          const map = new Map()
          records.forEach(r => {
            const id = r.uId || r.uid || r.userId
            const name = r.checker || r.username || r.realName || r.real_name
            if (id && !map.has(id)) map.set(id, name || `用户${id}`)
          })
          this.userOptions = Array.from(map, ([id, name]) => ({ id, realName: name }))
        } catch { this.userOptions = [] }
      } finally {
        this.userLoading = false
      }
    },

    onSearch() {
      this.query.current = 1
      this.fetchList()
    },

    onReset() {
      this.query = { checkNo: '', checkResult: '', current: 1, size: 5 }
      this.fetchList()
    },

    onPageChange(page) {
      const totalPages = Math.max(1, Math.ceil(this.total / this.query.size))
      const next = Math.min(Math.max(1, page), totalPages)
      if (next === this.query.current) return
      this.query.current = next
      this.fetchList()
    },

    onPageSizeChange() {
      this.query.current = 1
      this.fetchList()
    },

    // 获取分页范围信息
    getPageRange() {
      const start = (this.query.current - 1) * this.query.size + 1
      const end = Math.min(this.query.current * this.query.size, this.total)
      return { start, end }
    },

    async onAdd() {
      this.resetAddForm()
      await this.fetchUsers()
      this.addVisible = true
    },

    async submitAdd() {
      const { uId, checkTime, productCount, stockQuantity, checkTotal, remark } = this.addForm
      if (!uId || !checkTime || !productCount || stockQuantity === undefined || checkTotal === undefined) {
        ElMessage.error('请填写必填项')
        return
      }
      try {
        await addInventoryCheck({ uId, checkTime, productCount, stockQuantity, checkTotal, remark })
        ElMessage.success('新增成功')
        this.addVisible = false
        this.fetchList()
      } catch (e) {
        // 错误统一由 http 拦截器提示
      }
    },

    resetAddForm() {
      this.addForm = {
        checkNo: '',
        uId: '',
        checkTime: new Date().toISOString().split('T')[0], // 默认今天
        productCount: 1,
        stockQuantity: 0,
        checkTotal: 0,
        remark: ''
      }
    },

    async viewDetail(row) {
      if (!row?.id) return
      try {
        const res = await getInventoryCheckDetail(row.id)
        this.detailData = res.data?.data || {}
        this.detailVisible = true
      } catch (e) {
        ElMessage.error('获取详情失败')
      }
    },

    async onExport() {
      try {
        const params = {
          checkNo: this.query.checkNo || undefined,
          checkResult: this.query.checkResult === '' ? undefined : this.query.checkResult,
        }
        await exportInventoryCheck(params)
        ElMessage.success('导出成功')
      } catch (e) {
        ElMessage.error('导出失败')
      }
    },

    getResultClass(result) {
      if (result === 0) return 'status-profit'; // 盘盈
      if (result === 1) return 'status-loss';   // 盘亏
      if (result === 2) return 'status-normal'; // 正常
      return '';
    },

    getResultText(result) {
      const resultMap = {
        0: '盘盈',
        1: '盘亏',
        2: '正常'
      }
      return resultMap[result] || '未知'
    },

    getProfitLossClass(profitLoss) {
      if (profitLoss > 0) return 'profit';
      if (profitLoss < 0) return 'loss';
      return 'normal';
    },

    formatProfitLoss(profitLoss) {
      if (profitLoss === undefined || profitLoss === null) return '-'
      if (profitLoss > 0) return `+${profitLoss}`
      return profitLoss.toString()
    },

    formatDate(dateStr) {
      if (!dateStr) return '-'
      console.log('格式化时间:', dateStr, typeof dateStr)
      try {
        // 如果已经是字符串格式的日期，直接返回
        if (typeof dateStr === 'string' && dateStr.match(/^\d{4}-\d{2}-\d{2}$/)) {
          return dateStr
        }
        // 如果是时间戳或其他格式，转换为日期
        const date = new Date(dateStr)
        if (isNaN(date.getTime())) {
          return dateStr
        }
        return date.toLocaleDateString('zh-CN')
      } catch (e) {
        console.error('时间格式化错误:', e, dateStr)
        return dateStr
      }
    },

    // 从盘点编号中提取时间（备用方案）
    extractTimeFromCheckNo(checkNo) {
      if (!checkNo) return '-'
      try {
        // 盘点编号格式：KCPD203506190003
        // 提取日期部分：20350619
        const match = checkNo.match(/KCPD(\d{8})/)
        if (match) {
          const dateStr = match[1]
          const year = dateStr.substring(0, 4)
          const month = dateStr.substring(4, 6)
          const day = dateStr.substring(6, 8)
          return `${year}-${month}-${day}`
        }
        return '-'
      } catch (e) {
        console.error('从盘点编号提取时间失败:', e)
        return '-'
      }
    },

    // 获取显示用的盘点时间
    getDisplayCheckTime(item) {
      if (item.checkTime) {
        return this.formatDate(item.checkTime)
      }
      // 如果checkTime为null，尝试从盘点编号提取
      return this.extractTimeFromCheckNo(item.checkNo)
    }
  }
}
</script>

<style scoped>
.inventory-count-container {
  padding: 20px;
  background-color: #f5f7fa;
}

.controls-section {
  display: flex;
  gap: 16px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 20px;
  align-items: center;
}

.btn-new {
    background-color: #409eff;
    color: white;
    border: none;
    padding: 8px 16px;
    border-radius: 4px;
    cursor: pointer;
}

.filters {
    display: flex;
    gap: 16px;
    align-items: center;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item label {
  font-size: 14px;
}

.filter-item input, .filter-item select {
  padding: 8px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.filter-item input {
    width: 200px;
}

.actions {
  margin-left: auto;
}

.btn-primary {
  background-color: #409eff;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}

.btn-secondary {
  background-color: #fff;
  color: #606266;
  border: 1px solid #dcdfe6;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-left: 10px;
}

.table-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f8f9fa;
}

.link-style {
    color: #409eff;
    cursor: pointer;
}

.status-profit { color: #f56c6c; }
.status-loss { color: #f56c6c; }
.status-normal { color: #67c23a; }

.profit { color: #67c23a; }
.loss { color: #f56c6c; }
.normal { color: #909399; }

.footer-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  background-color: #fff;
  padding: 10px 20px;
  border-radius: 8px;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination-info {
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.pagination {
  display: flex;
  align-items: center;
  gap: 8px;
}

.pagination button {
  padding: 6px 12px;
  border: 1px solid #dcdfe6;
  background-color: #fff;
  cursor: pointer;
  border-radius: 4px;
}

.pagination button.active {
  background-color: #409eff;
  color: white;
  border-color: #409eff;
}

.pagination select {
  padding: 6px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

/* 弹窗样式 */
.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.form-item .label {
  font-weight: 500;
  color: #333;
}

.form-item .field {
  flex: 1;
}

.detail-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.detail-item .label {
  font-weight: 500;
  color: #666;
  font-size: 14px;
}

.detail-item .value {
  color: #333;
  font-size: 14px;
}
</style>
